﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Messaging;
namespace CardID
{
    public partial class InforTransaction : UserControl
    {
        MessageQueue messageQueue = null;
        const string pathQueue = @".\Private$\PortQueue";
        Thread receiveThread = null;
        static AutoResetEvent wait = null;
        localhost.ExecutePaymentResponse resultResponse = null;
        public InforTransaction()
        {
            InitializeComponent();
            this.SuspendLayout();
            this.Name = "Information";
            init();
            this.Visible = false;
            this.Enabled = false;
            //this.carIDText.Enabled = false;
           
        }
        public void init()
        {
            if (MessageQueue.Exists(pathQueue))
                messageQueue = new MessageQueue(pathQueue);
            else
                messageQueue = MessageQueue.Create(pathQueue);
            wait = new AutoResetEvent(false);
            

        }
        public delegate void set(localhost.ExecutePaymentResponse a);
        private delegate void LogMessageDelegate(string text);
        public void logMessage(string text)
        {
            if (InvokeRequired)
            {
                Invoke(new LogMessageDelegate(logMessage), text);
            }
            else
            {
                carIDText.Text = text + Environment.NewLine;
            }
           
        }
        public void Receive()
        {
            System.Messaging.Message mss = new System.Messaging.Message();
            int i = 1;
            string cardID;
            string text = "";
            string[] list;
            try
            {
                do
                {

                    Thread.Sleep(200);
                    // wait.WaitOne();
                    mss = messageQueue.Receive();

                    mss.Formatter = new XmlMessageFormatter(
                            new String[] { "System.String" });

                    cardID = mss.Body.ToString();

                    list = cardID.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);

                    text = list[0];
                    logMessage(text);

                } while (true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        // get All message in queue;
        public void ReadAllMessage()
        {
            System.Messaging.Message[] list = messageQueue.GetAllMessages();
            string cardID;
            string[] result;
            string text;
            foreach (System.Messaging.Message mss in list)
            {

                mss.Formatter = new XmlMessageFormatter(
                    new String[] { "System.String" });

                cardID = mss.Body.ToString();

                result = cardID.Split(new char[] { '@' }, StringSplitOptions.RemoveEmptyEntries);

                text = result[0];
                logMessage(text);
            }
        }
        private void nextBt_Click(object sender, EventArgs e)
        {
            int userId;
            int amount;
            localhost.ExecutePaymentResponse executeResponse = null;
            if (carIDText != null && carIDText.Text != "")
            {
            
                //send request Service
                message.Text = "Waitting for request....";
                localhost.MakePaymentResponse makeResponse = null;
                while (makeResponse == null)
                {
                    Thread.Sleep(500);
                    makeResponse = ServiceClient.sendRequest();
                }
                // check response and send information
                if (makeResponse.ack)
                {
                    try
                    {
                        userId = Int32.Parse(carIDText.Text);
                        amount = Int32.Parse(amountText.Text);
                        message.Text = "Waitting...We will execute and send Activation Code";
                       
                        while (executeResponse == null)
                        {
                            Thread.Sleep(300);
                            executeResponse = ServiceClient.excuteRequest(makeResponse.tokenID, userId, amount);
                            
                        }
                        if (executeResponse.ack)
                        {
                            resultResponse = executeResponse;
                            changeControlTo("requestControl");
                            //receiveThread.Abort();
                        }
                        else
                        {
                            MessageBox.Show("Request to execute failed.Please try again", "Infomation transaction", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Infomation transaction", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    MessageBox.Show("Request failed.Please try again", "Infomation transaction", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                }

            }
            else
            {
                MessageBox.Show("Input can not be null", "Infomation transaction", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void backBT_Click(object sender, EventArgs e)
        {

            changeControlTo("startControl");

        }
        /*
        public void requestService()
        {
            localhost.MakePaymentResponse makeResponse = null;
            bool isRequestSuccess = false;
            bool isRequest = true;
            while (isRequest)
            {
                try
                {
                    //makeResponse = sendRequest();
                    
                    if (makeResponse.ack == true)
                    {
                        //resultInfo.Text = makeResponse.paymentInfo;
                        isRequestSuccess = true;
                        break;
                    }
                }
                catch (Exception ex)
                {
                    if (DialogResult.Cancel == MessageBox.Show("Can not request to Server", "Request Server",
                                                       MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                    {
                        //resultInfo.Text = "Can not request to Service";
                        isRequest = false;
                        break;
                    }
                }
            }
        }
         * */
        public delegate void passData(string a,string b);
        public void changeControlTo(string nextNameControl)
        {
            this.Visible = false;
            this.Enabled = false;
            Control[] list = this.Parent.Controls.Find(nextNameControl, true);
            Control result = null;
            
            if (list.Length != 0)
            {
                result = list[0];
                result.Visible = true;
                result.Enabled = true;
                if (nextNameControl == "requestControl")
                {
                    requestControl request = (requestControl) result;
                    set passData = new set(request.getResponse);
                    passData(resultResponse);
                }
            }
        }
        // handle enable changed
        private void InforTransaction_EnabledChanged(object sender, EventArgs e)
        {
            if (this.Enabled)
            {
                if (receiveThread == null || (receiveThread != null && receiveThread.IsAlive == false))
                {
                    receiveThread = new Thread(new ThreadStart(Receive));
                    receiveThread.IsBackground = true;
                    receiveThread.Start();
                }
            }
            else
            {
                receiveThread.Abort();
                receiveThread = null;
            }
        }
       
        
    }
}
